﻿using System;
using System.Web;
using System.Collections;
using System.Web.Security;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace MikeKappel.Com.CS.HttpModules
{
    /// <summary>
    /// Summary description for GoogleAnalytics
    /// Google Analytics Http Module
    /// <configuration>
    /// <appSettings>
    /// <add key="GoogleAnalyticsWebPropertyID" value="CODE-FROM-GOOGLE" />
    /// <add key="GoogleAnalyticsMode" value="YOUR.DOMAIN.NAME" />
    /// <add key="GoogleAnalyticsDomain" value="MultiDomain" /> or "SingleDomain" or "MultiSubdomain"
    /// </appSettings>
    ///  <location>
    ///    <system.web>
    ///      <httpModules>
    ///        <add name="GoogleAnalyticsModule" type="MikeKappel.Com.CS.HttpModules.GoogleAnalyticsModule" />
    ///      </httpModules>
    ///    </system.web>
    ///  </location>
    ///  <system.webServer>
    ///    <modules>
    ///      <remove name="ScriptModule" />
    ///      <add name="GoogleAnalyticsModule" type="MikeKappel.Com.CS.HttpModules.GoogleAnalyticsModule" />
    ///    </modules>
    ///  </system.webServer>
    ///</configuration>
    /// </summary>
    public class GoogleAnalyticsModule : IHttpModule
    {
        public GoogleAnalyticsModule()
        {

        }

        public String ModuleName
        {
            get { return "GoogleAnalyticsModule"; }
        }

        /// <summary>
        /// In the Init function, register for HttpApplication events by adding your handlers.
        /// </summary>
        /// <param name="application"></param>
        public void Init(HttpApplication application)
        {
            application.BeginRequest += (new EventHandler(Application_BeginRequest));
        }

        /// <summary>
        /// Your BeginRequest event handler. 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void Application_BeginRequest(Object source, EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            MikeKappel.Com.CS.RewrittenUri uri = new MikeKappel.Com.CS.RewrittenUri(application.Request.Url.OriginalString);
            if (uri.File.Extension == RewrittenUri.FileExtensionType.asp
                || uri.File.Extension == RewrittenUri.FileExtensionType.aspx
                || uri.File.Extension == RewrittenUri.FileExtensionType.php
                || uri.File.Extension == RewrittenUri.FileExtensionType.htm 
                || uri.File.Extension == RewrittenUri.FileExtensionType.html)
                application.Response.Filter = new StreamFilter(application.Response.Filter, new GoogleAnalyticsFilter());
        }
        public void Dispose()
        {

        }
    }
}